<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRolesDialog = true"> 添加角色</el-button>
        </el-col>
      </el-row>
      <el-table border stripe style="width: 100%" :data="rolesList" v-loading="getLoading" class="box">
        <el-table-column type="expand">
          <template v-slot="{row}">
            <el-row :key="item.id" v-for="item in row.children" class="rolesList rolesList1">
              <!--一级-->
              <el-col :span="5">
                <el-tag closable @close="tagClose(item,row)">{{item.authName}}</el-tag><i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row :key="item2.id" v-for="item2 in item.children" class="rolesList rolesList2">
                  <!--二级-->
                  <el-col :span="10">
                    <el-tag type="success" closable @close="tagClose(item2,row)">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="14">
                    <el-row class="rolesList rolesList3">
                      <!--三级-->
                      <el-col>
                        <el-tag :key="item3.id" v-for="item3 in item2.children" type="warning" closable @close="tagClose(item3,row)">{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>

              </el-col>

            </el-row>

          </template>
        </el-table-column>
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{row}">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="small" :loading="row.setRoleLoadingBtn" @click="setRolesShow(row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="small" :loading="row.delLoading" @click="delRoles(row)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="small" :loading="row.setPowerLoadingBtn" @click="setPowerShow(row)">分配权限</el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialog" width="50%" @close="addRolesClosed" prop="addFormRef" :close-on-click-modal="false">
      <!-- 内容主体区域 -->
      <el-form :model="addRolesForm" label-width="100px" @keyup.enter.native="addRoles()" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="addRolesForm.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()" :loading="addLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog title="修改用户" :visible.sync="setRolesDialog" width="50%" @close="setRolesDialogClosed" :close-on-click-modal="false">
      <el-form :model="editForm" @keyup.enter.native="setRoles()" ref="setRoles" label-width="100px" :rules="editFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="editForm.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="setRoles()" :loading="setLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setPowerDialog" width="50%" @close="setPowerDialogClosed" :close-on-click-modal="false">
      <el-tree ref="tree" :data="treeList" show-checkbox node-key="id" :props="defaultProps" default-expand-all :default-checked-keys="treeListSelect">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setPowerDialog = false">取 消</el-button>
        <el-button type="primary" @click="setPower()" :loading="setPowerLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      getLoading: false,
      addLoading: false,
      setLoading: false,
      setPowerLoading: false,
      addRolesDialog: false,
      setRolesDialog: false,
      setPowerDialog: false,
      // 权限列表
      treeList: [],
      // 默认选中数组
      treeListSelect: [],

      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      rolesList: [],
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {

      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }

        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }

        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }

        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }

        ]

      }

    }
  },

  created () { // 进入页面就开始执行
    this.getRolesList()
  },

  components: {// 组件
  },

  computed: {// 计算属性是属性调用，而methods是函数调用
  },

  methods: { // 存储方法，处理复杂逻辑}
    getRolesList () {
      this.getLoading = true
      this.$http.get('roles/').then(res => {
        res = res.data

        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败！')
        }

        this.rolesList = res.data
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.getLoading = false
      })
    },
    addRolesClosed () {
      this.$refs.addFormRef.resetFields()
    },
    setRolesDialogClosed () {
      this.$refs.setRoles.resetFields()
    },
    setPowerDialogClosed () {
      this.treeListSelect = []
    },

    addRoles () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.addLoading = true
        this.$http.post('roles/', this.addRolesForm).then(res => {
          res = res.data

          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败！')
          }
          this.getRolesList()
          this.addRolesDialog = false
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.addLoading = false
        })
      })
    },
    delRoles (row) {
      this.$set(row, 'delLoading', true)
      this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$http.delete('roles/' + row.id).then(res => {
          res = res.data

          if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败！')
          }

          this.$message.success('删除用户成功！')

          this.getRolesList()
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.$set(row, 'delLoading', false)
        })
      }).catch(() => {
        this.$set(row, 'delLoading', false)
      })
    },

    setRoles () {
      this.$refs.setRoles.validate(valid => {
        if (!valid) return
        this.setLoading = true
        this.$http.put('roles/' + this.editForm.roleId, this.editForm).then(res => {
          res = res.data
          if (res.meta.status !== 200) {
            return this.$message.error('修改角色失败！')
          }
          this.$message.success('修改角色成功！')
          this.setRolesDialog = false
          this.getRolesList()
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.setLoading = false
        })
      })
    },
    setRolesShow (row) {
      this.$set(row, 'setRoleLoadingBtn', true)
      this.$http.get('roles/' + row.id).then(res => {
        res = res.data

        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败！')
        }
        this.editForm = res.data
        this.setRolesDialog = true
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.$set(row, 'setRoleLoadingBtn', false)
      })
    },
    tagClose (tag, row) {
      // function queryList (json) {
      //   for (var i = 0; i < json.length; i++) {
      //     var sonList = json[i].children

      //     if (sonList) {
      //       sonList.splice(sonList.indexOf(tag), sonList.indexOf(tag) === -1 ? 0 : 1)
      //       queryList(sonList)
      //     }
      //   }
      // }

      this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // queryList(this.rolesList)

        this.$http.delete('roles/' + row.id + '/rights/' + tag.id).then(res => {
          res = res.data
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败！')
          }
          this.$message.success('删除权限成功！')
          row.children = res.data
          // for (var i = 0; i < row.children.length; i++) {
          //   for (var j = 0; j < row.children[i].children.length; j++) {
          //     if (row.children[i].children[j].children.length === 0) {
          //       console.log(row.children[i].children, row.children[i].children[j])
          //       row.children[i].children.splice(row.children[i].children.indexOf(row.children[i].children[j]), 1)
          //     }
          //   }
          // }
          // for (var k = 0; k < row.children.length; k++) {
          //   if (row.children[k].children.length === 0) {
          //     row.children.splice(row.children.indexOf(row.children[k]), 1)
          //   }
          // }
        }).catch(err => {
          this.$message.error(err || '错误')
        })
      }).catch(() => {

      })
    },
    setPowerShow (row) {
      this.$set(row, 'setPowerLoadingBtn', true)
      this.$http.get('rights/' + 'tree').then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('获取权限列表失败！')
        }
        this.treeList = res.data
        this.setPowerDialog = true
        // 保存目前的角色信息
        this.PowerInfo = row
        this.queryList(row.children)
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.$set(row, 'setPowerLoadingBtn', false)
      })
    },
    setPower () {
      this.setPowerLoading = true
      const arr = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
      this.$http.post('roles/' + this.PowerInfo.id + '/rights', { rids: arr.toString() }).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('修改权限列表失败！')
        }
        this.$message.success('修改权限列表成功！')
        this.setPowerDialog = false
        this.getRolesList()
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.setPowerLoading = false
      })
    },
    queryList (node) {
      for (var i = 0; i < node.length; i++) {
        if (!node[i].children) {
          this.treeListSelect.push(node[i].id)
        } else {
          this.queryList(node[i].children)
        }
      }
    }
  },
  props: []

}
</script>
<style lang='less' scoped>
.rolesList {
  display: -webkit-flex flex; /* Safari */

  display: flex;
  align-items: center;

  text-align: center;
  border-bottom: 1px solid #ebeef5;
}
.rolesList:nth-last-child(1) {
  border-bottom: 0px solid #ebeef5;
}

.rolesList1 .el-tag {
  margin: 20px 0;
}
.rolesList3 {
  text-align: left;
  border-bottom: 0px solid #ebeef5;
}
.rolesList1 {
  padding: 5px 0;
}
.rolesList2 {
  padding: 10px 0;
}
.rolesList2 .el-tag {
  margin: 10px 0;
}
.rolesList3 .el-tag {
  margin: 5px;
}
/deep/ .box .el-table__expanded-cell {
  padding: 10px;
}
</style>
